package com.hourse.platform.utils;

import com.alibaba.fastjson.JSONObject;
import com.hourse.platform.exception.ValidateException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;

/**
 * 描述: 字段校验工具类
 */
public class BeanTools {

    private final static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * @param object 需要校验的对象
     * @return : void
     * @功能描述: 【JSR 303 校验】
     */
    public static void Validate(Object object) throws ValidateException {
        Set<ConstraintViolation<Object>> violations = validator.validate(object);
        Iterator<ConstraintViolation<Object>> iter = violations.iterator();
        if (iter.hasNext()) {
            String errMessage = iter.next().getMessage();
            throw new ValidateException(errMessage);
        }
    }

    /**
     * @功能描述: 【VO 转 新的实体 并且校验】
     */
    public static Object BindEnity(Object object,Class clzss) throws ValidateException {

      BeanTools.Validate(object);
      Object obj = BindEnityUnValidate(object,clzss);
      return obj;
    }

  /**
   * @功能描述: 【VO 转 新的实体】
   */
    public static Object BindEnityUnValidate(Object object,Class clzss){

        return JsonTools.convertTo(object,clzss);
    }

  /**
   * @功能描述: 【OBJ 转 JSON】
   */
    public static JSONObject ToJson(Object object){

      return JSONObject.parseObject(JSONObject.toJSONString(object));
    }
}
